﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.IO;
using V2TEK.NET.SH.Silverlight.Charts.GanttHelper;
using System.Collections.ObjectModel;
using System.Windows.Browser;
using System.Xml;
using V2TEK.NET.SH.Silverlight.Charts.TreeGridHelper;

namespace V2TEK.NET.SH.Silverlight.GanttView
{
    public partial class MainPage : UserControl
    {
        private DataManagerBase dataManager = new RSDataManager();
        private GanttOutput output = new GanttOutput();

        private int IniColNum = 0;

        private string DispFormUrl = "";

        class ParamsReader : Dictionary<string, string>
        {
            private Dictionary<string, string> defInits = new Dictionary<string, string>();
            public ParamsReader()
            {
                 //<param name="InitParams" value="idField=ID,startDateField=PlanCD,
                //dueDateField=PlanSD,titleField=LinkTitleNoMenu,
                //percentCompleteField=PercentComplete,
                //listName={D1F51FC0-4E97-4FEC-A16A-8C38DD36BBE3},
                //viewName={24AE07EC-512E-4696-9C58-3C425B881FF4},
                //folder=,dataService=http://rshi1:25000/sites/project1/,dispFormUrl="/>
                defInits.Add("idField", "ID");
                defInits.Add("startDateField", "PlanCD");
                defInits.Add("dueDateField", "PlanSD");
                defInits.Add("titleField", "LinkTitleNoMenu");
                defInits.Add("percentCompleteField", "PercentComplete");
                defInits.Add("listName", "{D1F51FC0-4E97-4FEC-A16A-8C38DD36BBE3}");
                defInits.Add("viewName", "{24AE07EC-512E-4696-9C58-3C425B881FF4}");
                defInits.Add("folder", "");
                defInits.Add("dataService", "http://rshi1:25000/sites/project1/");
                defInits.Add("dispFormUrl", "");

            }

            public string this[string key]
            {
                get
                {
                    if (Application.Current.Host.InitParams.ContainsKey(key))
                    {
                        return Application.Current.Host.InitParams[key];
                    }
                    if (defInits.ContainsKey(key))
                        return defInits[key];
                    return "";
                }
            }
        }

        ParamsReader InitParams = new ParamsReader();

        public MainPage()
        {
            InitializeComponent();
            this.Gantt.ExpanderProvider = typeof(DynamicTaskExpander);


            DispFormUrl = InitParams["dispFormUrl"];

            this.dataManager.SetFields(InitParams["idField"],
                InitParams["titleField"],
                InitParams["startDateField"],
                InitParams["dueDateField"],
                InitParams["percentCompleteField"]);

            IniColNum = this.Gantt.GanttColumns.Count;

            dataManager.GetDataCompleted += new EventHandler(dataManager_GetDataCompleted);
            LoadData();


            if (InitParams.ContainsKey("debug") &&
                InitParams["debug"].ToUpper() == "TRUE")
            {
                this.mDownloadViewField.Visibility = System.Windows.Visibility.Visible;
                this.mDownloadViewData.Visibility = System.Windows.Visibility.Visible;
            }
        }

        void TreeGrid_ExpandChange(object sender, RowExpandEventArgs args)
        {
            if (args.IsExpand)
            {
                this.dataManager.GetZrcChild(InitParams["listName"],
                    InitParams["viewName"],
                    args.Expander);
            }
        }

        private void LoadData()
        {
            this.Gantt.IsLoading = true;
            this.Gantt.DataSource = null;
            this.Gantt.Update();
            dataManager.GetData(InitParams["listName"], InitParams["viewName"]);
        }

        void dataManager_GetDataCompleted(object sender, EventArgs e)
        {
            this.Gantt.IsLoading = false;
            if (this.dataManager.Data != null && this.dataManager.Data.Count > 0)
            {
                while (this.Gantt.GanttColumns.Count > IniColNum)
                {
                    this.Gantt.GanttColumns.RemoveAt(IniColNum);
                }

                foreach (var vf in this.dataManager.ViewFields)
                {
                    SharePointField field = this.dataManager.Fields[vf];
                    ExtendAttributeTextColumn column = new ExtendAttributeTextColumn();
                    column.Binding = new Binding("Data.ExtendAttributes");
                    column.Header = field.DisplayName;
                    column.ExtendAttributeKey = field.Name;
                    this.Gantt.GanttColumns.Add(column);
                }


                Gantt.DataSource = this.dataManager.Data;
                //this.Gantt.Zoom = (this.dataManager.Data[0].EndDate - this.dataManager.Data[0].StartDate).TotalMilliseconds / this.Gantt.TimeLine.ViewPortWidth;
                var result = from c in this.dataManager.Data where c.HasStartDate select c.StartDate;
                if (result.Count() > 0)
                {
                    var minStart = result.Min();
                    Gantt.Update(minStart);
                }
                else
                    Gantt.Update(DateTime.Now);
            }

            this.Gantt.TreeGrid.ExpandChange -= new ExpandChangeEventHandler(TreeGrid_ExpandChange);
            this.Gantt.TreeGrid.ExpandChange += new ExpandChangeEventHandler(TreeGrid_ExpandChange);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.Gantt.ZoomOut();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            this.Gantt.ZoomIn();
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            this.Gantt.NavigateToSeleteItem();
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ITaskDescriptor task = ((TaskEntryLayoutItem)((HyperlinkButton)sender).DataContext).Data;
                string url = string.Format(DispFormUrl, task.UniqueId);
                HtmlPage.Window.Eval("LoadItemInfo('" + url + "');");
            }
            catch
            {
            }
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            this.Gantt.ExpandAll();
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            this.Gantt.CollapseAll();
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            ChildWindow window = new ChildWindow();
            window.Height = this.ActualHeight / 2;
            window.Width = this.ActualWidth / 2;
            ListBox lb = new ListBox();
            window.Content = lb;
            foreach (var item in this.dataManager.Fields)
            {
                CheckBox lbi = new CheckBox();
                lbi.Content = item.Value.DisplayName;
                lbi.Tag = item.Value;
                lbi.IsChecked = this.dataManager.ViewFields.Contains(item.Key);
                lbi.Checked += new RoutedEventHandler(lbi_Checked);
                lbi.Unchecked += new RoutedEventHandler(lbi_Checked);
                lb.Items.Add(lbi);
            }
            window.Show();
        }

        void lbi_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            SharePointField field = chk.Tag as SharePointField;
            if (chk.IsChecked == true)
            {
                ExtendAttributeTextColumn column = new ExtendAttributeTextColumn();
                column.Binding = new Binding("Data.ExtendAttributes");
                column.Header = field.DisplayName;
                column.ExtendAttributeKey = field.Name;
                this.Gantt.GanttColumns.Add(column);
                this.dataManager.ViewFields.Add(field.ShortName);
            }
            else
            {
                foreach (var item in this.Gantt.GanttColumns)
                {
                    if (item is ExtendAttributeTextColumn)
                    {
                        ExtendAttributeTextColumn col = item as ExtendAttributeTextColumn;
                        if (col.ExtendAttributeKey == field.Name)
                        {
                            this.Gantt.GanttColumns.Remove(item);
                            this.dataManager.ViewFields.Remove(field.ShortName);
                            break;
                        }
                    }
                }

            }
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Project XML文档|*.xml";
            if (sfd.ShowDialog() == true)
            {
                Stream stream = sfd.OpenFile();
                byte[] buf = this.output.ToProjectXML(this.Gantt.DataSource as ObservableCollection<ITaskDescriptor>);
                stream.Write(buf, 0, buf.Length);
                stream.Close();
            }
        }

        private void Button_Click_8(object sender, RoutedEventArgs e)
        {
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
        }

        private void Button_Click_9(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            if (sfd.ShowDialog() == true)
            {
                Stream stream = sfd.OpenFile();
                var buf = System.Text.Encoding.UTF8.GetBytes(dataManager.ViewFieldXml.ToString());
                stream.Write(buf, 0, buf.Length);
                stream.Close();

            }

            MessageBox.Show("完成");
        }

        private void mDownloadViewData_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            if (sfd.ShowDialog() == true)
            {
                Stream stream = sfd.OpenFile();
                var buf = System.Text.Encoding.UTF8.GetBytes(dataManager.ViewDataXml.ToString());
                stream.Write(buf, 0, buf.Length);
                stream.Close();
            }
            MessageBox.Show("完成");
        }


    }


    public class RequireTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double time;
            if (double.TryParse(value.ToString(), out time))
            {
                if (parameter == null)
                    parameter = "天";
                switch (parameter.ToString())
                {
                    case "天":
                        return (TimeSpan.FromMilliseconds(time)).TotalDays;
                }

            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double time;
            if (double.TryParse(value.ToString(), out time))
            {
                if (parameter == null)
                    parameter = "天";
                switch (parameter.ToString())
                {
                    case "天":
                        return TimeSpan.FromDays(time).TotalMilliseconds;
                }

            }
            return value;
        }
    }


    public class DateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DateTime dt = (DateTime)value;
            if (dt == DateTime.MinValue)
                return "";
            return dt.ToString("M/d/yyyy");
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}
